package com.news.servlet.admin;

import com.news.model.User;
import com.news.service.UserService;
import com.news.service.impl.UserServiceImpl;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/admin/userAdd")
public class UserAddServlet extends HttpServlet {
    private UserService userService = new UserServiceImpl();

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            // 获取表单数据
            String username = request.getParameter("username");
            String password = request.getParameter("password");
            String realname = request.getParameter("realname");
            String email = request.getParameter("email");
            String admin = request.getParameter("admin");

            // 创建用户对象
            User user = new User();
            user.setUsername(username);
            user.setPassword(password);
            user.setRealname(realname);
            user.setEmail(email);
            user.setAdmin(admin);

            // 添加用户
            if (userService.addUser(user)) {
                request.getSession().setAttribute("message", "用户添加成功！");
                response.sendRedirect(request.getContextPath() + "/admin/userManage");
            } else {
                request.getSession().setAttribute("message", "用户添加失败！");
                response.sendRedirect(request.getContextPath() + "/admin/user_add.jsp");
            }
        } catch (Exception e) {
            request.getSession().setAttribute("message", "用户添加失败：" + e.getMessage());
            response.sendRedirect(request.getContextPath() + "/admin/user_add.jsp");
        }
    }
} 